package com.example.rwq_test.anno.customAnno.EventAnnotation;

import com.example.rwq_test.anno.customAnno.EventAnnotation.event.Event;
import com.example.rwq_test.anno.customAnno.EventAnnotation.hadler.AbstractHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;

/**
 * @Description
 * @Author renweiqiang
 * @Date 2024/4/28 上午11:21
 */
@Component
public class EventHandlerFactory implements InitializingBean {
    /**
     * 事件处理器map
     */
    private static final Map<EventTypeEnum,AbstractHandler> EVENT_HANDLER_MAP = new EnumMap<>(EventTypeEnum.class);
    /**
     * 上下文
     */
    private ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取事件处理器
     *
     * @param event
     * @return
     */
    public AbstractHandler getHandler(Event event) {
        if (event == null || event.getEventType() == null) {
            return null;
        }
        return EVENT_HANDLER_MAP.get(event.getEventType());
    }

    /**
     * 获取事件处理器
     *
     * @return
     */
    public AbstractHandler getHandler(EventTypeEnum eventType) {
        if (eventType == null) {
            return null;
        }
        return EVENT_HANDLER_MAP.get(eventType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String[] beanNames = applicationContext.getBeanNamesForType(AbstractHandler.class);
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            Class<?> clazz = bean.getClass();
            EventAnnotation annotation = clazz.getAnnotation(EventAnnotation.class);
            if (annotation == null) {
                System.out.println(clazz.getName() + " EventAnnotation is null.");
                continue;
            }
            EVENT_HANDLER_MAP.put(annotation.eventType(), (AbstractHandler) bean);
        }
    }
}
